package com.zysd.collection.scheduler.service.model.impl;

import cn.uncode.schedule.ConsoleManager;
import cn.uncode.schedule.core.TaskDefine;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lensyn.common.exception.entity.MsgException;
import com.zysd.collection.scheduler.entity.SchedulerTaskModel;
import com.zysd.collection.scheduler.service.model.SchedulerModelTaskService;
import com.zysd.collection.scheduler.system.enums.TaskStatus;
import com.zysd.collection.scheduler.system.job.SchedulerTaskForward;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 任务模板 定时任务 service实现
 *
 * @author liuht
 * @date 2017/10/19 14:27
 */
@Service
public class SchedulerModelTaskServiceImpl implements SchedulerModelTaskService {
    private final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    private static final Logger LOGGER = LoggerFactory.getLogger(SchedulerModelTaskServiceImpl.class);

    private static final String SUFFIX = "schedulerModelTask$";

    @Override
    public void startModelTask(SchedulerTaskModel model) {
        try {
            // 定义任务实体
            TaskDefine task = new TaskDefine();
            task.setTargetBean(SchedulerTaskForward.BEAN_NAME);
            task.setTargetMethod(SchedulerTaskForward.METHOD);
            task.setExtKeySuffix(SUFFIX + model.getId());
            task.setCronExpression(model.getCronExpression());
            task.setParams(gson.toJson(model));
            if (ConsoleManager.isExistsTask(task)) {
                // 更新
                ConsoleManager.updateScheduleTask(task);
            } else {
                // 新增
                task.setStartTime(new Date());
                ConsoleManager.addScheduleTask(task);
            }
        } catch (Exception e) {
            LOGGER.error("startModelTask failed.", e);
            throw new MsgException("启动定时任务失败");
        }
    }

    @Override
    public void stopModelTask(SchedulerTaskModel model) {
        try {
            // 定义任务实体
            TaskDefine task = new TaskDefine();
            task.setTargetBean(SchedulerTaskForward.BEAN_NAME);
            task.setTargetMethod(SchedulerTaskForward.METHOD);
            task.setExtKeySuffix(SUFFIX + model.getId());
            if (ConsoleManager.isRunning(task)) {
                task.setStatus(TaskDefine.STATUS_STOP);
                ConsoleManager.updateScheduleTask(task);
            } else {
                if (!ConsoleManager.isExistsTask(task)) {
                    throw new MsgException("任务不存在");
                }
                if (!ConsoleManager.isRunning(task)) {
                    throw new MsgException("任务处于停止状态");
                }
            }
        } catch (MsgException e) {
            throw new MsgException(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("stopModelTask failed.", e);
            throw new MsgException("停止定时任务失败");
        }
    }

    @Override
    public void deleteModelTask(SchedulerTaskModel model) {
        try {
            // 定义任务实体
            TaskDefine task = new TaskDefine();
            task.setTargetBean(SchedulerTaskForward.BEAN_NAME);
            task.setTargetMethod(SchedulerTaskForward.METHOD);
            task.setExtKeySuffix(SUFFIX + model.getId());
            if (ConsoleManager.isExistsTask(task)) {
                ConsoleManager.delScheduleTask(task);
            } else {
                throw new MsgException("任务不存在,无法删除");
            }
        } catch (MsgException e) {
            throw new MsgException(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("stopModelTask failed.", e);
            throw new MsgException("停止定时任务失败");
        }
    }

    @Override
    public TaskStatus modelTaskStatus(SchedulerTaskModel model) {
        TaskDefine task = new TaskDefine();
        task.setTargetBean(SchedulerTaskForward.BEAN_NAME);
        task.setTargetMethod(SchedulerTaskForward.METHOD);
        task.setExtKeySuffix(SUFFIX + model.getId());
        if (!ConsoleManager.isExistsTask(task)) {
            return TaskStatus.not_started;
        } else {
            if (ConsoleManager.isRunning(task)) {
                return TaskStatus.running;
            } else {
                return TaskStatus.stop;
            }
        }
    }
}
